// 获取请求地址
var requestType = "request";
// 应用版本
var version = "1.0.6";
//页面展示条数
var rows = 20;
// 图片的请求地址
//var filesHost = getRequestAddressUrl("filesHost");
var loginid = window.localStorage.getItem("uid");
//var loginid = "1000171372";

mui.plusReady(function() {
	// 存储父页面webViewId
	if(mui("#parentWebViewId").length == 0) {
		var inputBox = document.createElement('input');
		inputBox.id = "parentWebViewId";
		inputBox.style.display = "none";
		inputBox.type = "text"
		inputBox.value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
		document.body.appendChild(inputBox);
	} else {
		mui("#parentWebViewId")[0].value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
	}
});

var cssEl = document.createElement('style');
document.documentElement.firstElementChild.appendChild(cssEl);

function setPxPerRem(clientWidth) {
	var dpr = 1;
	//把viewport分成15份的rem，html标签的font-size设置为1rem的大小;

	if(!clientWidth) {
		clientWidth = document.documentElement.clientWidth;
	}

	var pxPerRem = clientWidth * dpr / 15;
	cssEl.innerHTML = 'html{font-size:' + pxPerRem + 'px!important;}';
}

// 处理横屏竖屏事件
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
window.addEventListener(evt, function() {
	// 竖屏
	if(window.orientation === 180 || window.orientation === 0) {
		if(typeof orientation180 == "function") {
			orientation180();
		}
	}
	// 横屏
	if(window.orientation === 90 || window.orientation === -90) {
		if(typeof orientation90 == "function") {
			orientation90();
		}
	}
}, false);
// 是否竖屏显示
// flg：true竖屏显示
function lockOrientation(flg) {
	if(flg) {
		plus.screen.lockOrientation("portrait-primary");
	}
}

// mui全局处理
mui.init({
	beforeback: function() {
		// 页面回调方法                                                        
		if(typeof beforeback === 'function') {
			beforeback.call();
		}
	}
});

// 设置json默认值
// defaults：默认值
// settings：返回值
function extendSettings(defaults, settings) {
	if(typeof(settings) != "object") {
		return defaults;
	} else {
		for(var o in defaults) {
			var addflg = true;
			var addobj;
			for(var n in settings) {
				if(o == n) {
					addflg = false;
					addobj = "";
					break;
				} else {
					addobj = o;
				}
			}

			if(addflg) {
				settings[addobj] = defaults[addobj];
			}
		}

		return settings;
	}
}
// 事件绑定
// settings.eventId：对象id
// settings.eventType：事件绑定类型，默认tap
// settings.eventFunction：触发方法体
function elementBindEvent(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventId)[0].addEventListener(settings.eventType, function() {
		if(settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};
// 群组上事件
// settings.eventObj：父容器id
// settings.eventType：事件绑定类型
// settings.targetObj：带绑定控件组样式
// settings.eventFunction：触发方法体
function elementBindEventByObj(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventObj).on(settings.eventType, "." + settings.targetObj, function() {
		if(settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};
// 页面跳转
// settings.pageUrl：页面url
// settings.postData：目标页面参数
// settings.aniShow：页面加载动态效果,默认为slide-in-right
function pageChange(settings) {
	if(!settings.postData) {
		settings.postData = {};
	}
	settings.postData.webViewId = plus.webview.currentWebview().id;
	var defaults = {
		aniShow: "slide-in-right",
		createNew: false
	};
	settings = extendSettings(defaults, settings);
	var isCreate = false;

	mui.openWindow({
		id: settings.pageUrl,
		url: settings.pageUrl,
		show: {
			autoShow: true, //页面loaded事件发生后自动显示，默认为true      
			aniShow: settings.aniShow, //页面显示动画，默认为”slide-in-right“；      
			duration: 200 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；    
		},
		createNew: settings.createNew,
		waiting: {
			autoShow: false
		},
		extras: settings.postData
	});
};
// 获取请求参数
// name：参数名称
function getQueryString(name) {
	var self = plus.webview.currentWebview();
	return self[name];
};
//生成32位随机码
function newGuid() {
	var guid = "";
	for(var i = 1; i <= 32; i++) {
		var n = Math.floor(Math.random() * 16.0).toString(16);
		guid += n;
	}
	return guid;
};
// 获取请求地址
function getRequestAddressUrl(addKey) {
	var retUrl = "";
	for(var i = 0; i < requestAddressList.length; i++) {
		if(requestAddressList[i].addressKey == addKey) {
			retUrl = requestAddressList[i].url;
			break;
		}
	}

	return retUrl;
};

// 组合json
function jsonjoin(sorJosn, tarJosn) {
	sorJosn.push = function(o) {
		if(typeof(o) == 'object')
			for(var p in o) this[p] = o[p];
	};
	sorJosn.push(
		tarJosn
	)

	return sorJosn;
};
// 调用父webview方法
// funName：方法名
// params：参数
function callParentWebViewFun(funName, params) {
	if(!params) {
		params = {};
	}
	var pageid = mui("#parentWebViewId")[0].value;
	mui.fire(plus.webview.getWebviewById(pageid), funName, params);
};

// 请求方法
// settings.url：请求路径
// settings.appurl：json请求路径
// settings.pastDate：参数json格式
// settings.addressKey：请求地址key，默认request
// settings.nativeFlg:是否为原生，默认false
// settings.requestType:POST GET 默认GET
// settings.addressUrl:请求地址，默认请求地址为 requestType  loginType-登陆   appType -应用中心  addFriend 即时通讯加好友
// settings.getapp  根据当前登录人身份获取应用  app
// callBackFun：回调方法
function crossDomainAjax(settings, callBackFun) {
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var defaults = {
		addressKey: "request",
		nativeFlg: false,
		isAllData: false
	};
	if(!settings.addressUrl) {
		settings.addressUrl = "requestType";
	}
	if(!settings.appurl) {
		settings.appurl = settings.url;
	}
	if(!settings.requestType) {
		settings.requestType = "GET";
	}
	settings = extendSettings(defaults, settings);
	var temp = new Date().getTime();
	var requestUrl;
	if(requestType == "request") {
		var temp = new Date().getTime();
		if(settings.addressUrl == 'loginType') {
			requestUrl = getRequestAddressUrl("login");
		} else if(settings.addressUrl == 'appType') {
			requestUrl = getRequestAddressUrl("appType") + settings.url;
		} else if(settings.addressUrl == 'testline') {
			requestUrl = getRequestAddressUrl("testline") + settings.url;
		} else if(settings.addressUrl == 'resourceCentre') {
			requestUrl = getRequestAddressUrl("resourceCentre") + settings.url;
		} else {
			requestUrl = getRequestAddressUrl(requestType) + settings.url;
		}
	} else {
		requestUrl = appurl + settings.appurl;
	}
	if(settings.requestType == 'GET') {

		// 处理参数
		for(var o in settings.pastDate) {
			if(requestUrl.indexOf('?') != -1) {
				requestUrl = requestUrl + "&" + o + "=" + settings.pastDate[o];
			} else {
				requestUrl = requestUrl + "?" + o + "=" + settings.pastDate[o];
			}
		}
	}
	console.log("requestUrl--》" + requestUrl);
	if(!settings.nativeFlg || (settings.nativeFlg && requestType == "request")) {
		var appAjax = new XMLHttpRequest();
		appAjax.open(settings.requestType, requestUrl, true);

		if(!isEmpty(settings.authorization)) {
			logText("settings.authorization==>" + settings.authorization)
			appAjax.setRequestHeader('authorization', settings.authorization)
		}

		if(settings.requestType == "GET") {
			if(!isEmpty(settings.getapp)) {
				appAjax.setRequestHeader("Wd-Token", window.localStorage.getItem("Wd-Token"));
			}
			appAjax.send("");
		} else if(settings.requestType == "POST") {
			appAjax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
			var jsonData = JSON.stringify(settings.pastDate);
			appAjax.send(jsonData);
		}
		appAjax.onreadystatechange = function() {
			if(appAjax.readyState == 4) {
				var responseDate = JSON.parse(appAjax.responseText);
				console.log(appAjax.responseText);
				if(settings.isAllData) {
					callBackFun.call('', responseDate);
				} else {
					if(!isEmpty(responseDate.status) && responseDate.status == 1) {
						if(callBackFun) {
							callBackFun.call('', responseDate.result);
						}
					} else {
						plus.nativeUI.closeWaiting();
						mui.toast(responseDate.result);
					}
				}
				appAjax = null;
			}
		}
	} else {
		var jsonDataUrl = requestUrl;
		plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function(fs) {
			fs.root.getFile(jsonDataUrl, {
				create: true
			}, function(fileEntry) {
				fileEntry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					fileReader.readAsText(file, 'utf-8');
					fileReader.onloadend = function(evt) {
						var responseDate = eval("(" + evt.target.result + ")");
						if(callBackFun) {
							callBackFun.call('', responseDate);
						}
					}
				});
			});
		});
	}
}
// 获取相邻元素(内部方法)
function getNearEle(ele, type) {
	type = type == 1 ? "previousSibling" : "nextSibling";
	var nearEle = ele[type];
	while(nearEle) {
		if(nearEle.nodeType === 1) {
			return nearEle;
		}
		nearEle = nearEle[type];
		if(!nearEle) {
			break;
		}
	}
	return null;
}
// 获取当前对象的上一个元素
// ele：当前对象
function prev(ele) {
	return getNearEle(ele, 1);
}
// 获取当前对象的下一个元素
// ele：当前对象
function next(ele) {
	return getNearEle(ele, 0);
}
// 获得匹配元素集合中每个元素前面的所有同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function prevAll(ele, tarEle) {
	var prevEles = [];
	var ele = getNearEle(ele, 1);
	return pushEle(prevEles, ele, tarEle);

	function pushEle(prevEles, ele, tarEle) {
		if(ele) {
			if(tarEle) {
				if(ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					prevEles.push(ele);
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				}
			} else {
				prevEles.push(ele);
				ele = getNearEle(ele, 1);
				pushEle(prevEles, ele, tarEle);
			}
		}
		return prevEles;
	}
}
// 获得匹配元素集合中每个元素的所有跟随的同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function nextAll(ele, tarEle) {
	var nextEles = [];
	var ele = getNearEle(ele, 0);
	return pushEle(nextEles, ele, tarEle);

	function pushEle(nextEles, ele, tarEle) {
		if(ele) {
			if(tarEle) {
				if(ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					nextEles.push(ele);
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				}
			} else {
				nextEles.push(ele);
				ele = getNearEle(ele, 0);
				pushEle(nextEles, ele, tarEle);
			}
		}
		return nextEles;
	}
}
// 当前对象前插入元素、newEle放到tarEle前面
function insertBefore(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if(!parent) {
		parent = tarEle;
	}
	parent.insertBefore(newEle, tarEle);
}
// 当前对象后插入元素、newEle放到tarEle后面
function insertAfter(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if(!parent) {
		parent = tarEle;
	}
	if(parent.lastChild == tarEle) {
		parent.appendChild(newEle);
	} else {
		parent.insertBefore(newEle, tarEle.nextSibling);
	}
}
// 获取指定元素 ele.find(tarEle)
function find(ele, tarEle) {
	var tarEles = [];
	var nodes = ele.childNodes;
	return getEle(tarEles, nodes, tarEle);

	function getEle(tarEles, nodes, tarEle) {
		for(var i = 0; i < nodes.length; i++) {
			if(nodes[i].nodeName.toLowerCase() == tarEle || nodes[i].className == tarEle || nodes[i].id == tarEle) {
				tarEles.push(nodes[i]);
				getEle(tarEles, nodes[i].childNodes, tarEle);
			} else {
				getEle(tarEles, nodes[i].childNodes, tarEle);
			}
		}
		return tarEles;
	}
}
// 获取元素位置
// tarEle：当前元素
function index(tarEle) {
	var parent = tarEle.parentNode;
	var eleArr = parent.childNodes;
	var index = 0;
	for(var i = 0; i < eleArr.length; i++) {
		if(eleArr[i] == tarEle) {
			index = i;
			break;
		}
	}
	return index;
}
// 移除元素
// ele:当前元素
function remove(ele) {
	var parent = ele.parentNode;
	parent.removeChild(ele);
}
// 循环数组
function foreach(array, func) {
	for(var i = 0; i < array.length; ++i) {
		func(array[i]);
	}
};
// 滚动到对象底部
function scrollBottom(obj) {
	obj.scrollTop = obj.scrollHeight;
}
// 加载模板H5用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplate(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('-')[0].toLowerCase();
	var languageData;
	var appAjaxLanguage = new XMLHttpRequest();
	appAjaxLanguage.open('GET', appurl + settings.languageUrl + "_" + languageType + ".properties", true);
	appAjaxLanguage.send(null);
	appAjaxLanguage.onreadystatechange = function() {
		if(appAjaxLanguage.readyState == 4) {
			languageDate = eval("(" + appAjaxLanguage.responseText + ")");
			localStorage[settings.languageUrl] = appAjaxLanguage.responseText;
			var appAjax = new XMLHttpRequest();
			appAjax.open('GET', appurl + settings.templateUrl + ".html", true);
			appAjax.send(null);
			appAjax.onreadystatechange = function() {
				if(appAjax.readyState == 4) {
					var responseData = appAjax.responseText;

					responseData = changenDataByLanguage(responseDate, languageData);

					document.getElementById(settings.templateId).innerHTML = responseData;

					if(settings.loadFunction) {
						settings.loadFunction.call(null, settings.parameters, languageData);
					}
					appAjax = null;
				}
			}

			appAjaxLanguage = null;
		}
	}
};
// 获取国际化信息原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function(fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function(fileEntry) {
			fileEntry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					localStorage[settings.languageUrl] = evt.target.result;
				};
			});
		});
	});
	setTimeout(function() {
		settings.languageDataFn.call('', getLanguageDataAgain(settings.languageUrl, settings));
	}, 100)

};
// 单独获取国际化信息
//key:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataAgain(key, settings) {
	//	console.log("key"+key);
	if(localStorage[key] != "") {
		return eval("(" + localStorage[key] + ")");
	} else {
		return getLanguageDataNative(settings);
	}
}

// 加载模板原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplateNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";
	var templateUrl = appurl + settings.templateUrl + ".html";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function(fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function(fileEntry) {
			fileEntry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					var languageData = eval('(' + evt.target.result + ')');
					localStorage[settings.languageUrl] = evt.target.result;
					fs.root.getFile(templateUrl, {
						create: true
					}, function(fileEntry) {
						fileEntry.file(function(file) {
							var fileReader = new plus.io.FileReader();
							fileReader.readAsText(file, 'utf-8');
							fileReader.onloadend = function(evt) {
								var responseData = changenDataByLanguage(evt.target.result, languageData);
								document.getElementById(settings.templateId).innerHTML = responseData;

								if(settings.loadFunction) {
									settings.loadFunction.call(null, settings.parameters, languageData);
								}
							}
						})
					})
				}
			});
		});
	});
}

// 替换语言信息
function changenDataByLanguage(responseData, languageData) {
	for(var o in languageData) {
		responseData = responseData.replace(new RegExp("\\{{" + o + "\\}}", "g"), languageData[o]);
	}
	return responseData;
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy-MM-dd HH:mm 的基本格式
function formatCreateTimeByBase(createTime) {
	if(!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "-" + month + "-" + day + " " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

//格式化时间 
//dateTime 需要格式化的时间（格式为：2016-08-05 11:00:00）
// 格式化之后返回时间的格式为：2016年08月05日 11:00
function formatDateTime(dateTime) {
	console.log("dateTime------>" + dateTime);
	if(!dateTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(dateTime.length == 19) {
		var year = dateTime.slice(0, 4);
		var month = dateTime.slice(5, 7);
		var day = dateTime.slice(8, 10);
		var hour = dateTime.slice(11, 13);
		var minute = dateTime.slice(14, 16)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return dateTime;
	}
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy年MM月dd日 HH:mm 的基本格式
//createTime 服务器返回时间
// value 国际化后的时间标志 （年，月，日）
function formatCreateTimeByChina(createTime) {
	if(!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

/**
 * Description: 加载缓存
 *    后台返回值格式：{"info":[{"codeclass":"XBDM","version":0,"data":[{"code":"1","codedesc":"男"},{"code":"2","codedesc":"女"}]},{"codeclass":"XXDM","version":0,"data":[{"code":"1","codedesc":"A"},{"code":"2","codedesc":"B"}]}]}
 * @param codeclass_arr 将要加载至缓存的codeclass代码组织成数组形式参数
 */
function setCodeMap(codeclass_arr, callback) {
	var url = getRequestAddressUrl("codemap");
	var param_json = {};
	for(var j = 0; j < codeclass_arr.length; j++) {
		param_json[codeclass_arr[j]] = getCodeClassVersion(codeclass_arr[j]);
	}
	var param_str = JSON.stringify(param_json);
	$.ajax({
		type: "POST",
		url: url,
		data: "clv=" + param_str,
		dataType: "json",
		success: function(data) {
			if(data.info != undefined && data.info != null && data.info.length > 0) {
				for(var i = 0; i < data.info.length; i++) {
					var codeClass = data.info[i].codeclass;
					delete data.info[i]["codeclass"];
					store.setItem(codeClass, "{\"data\":" + JSON.stringify(data.info[i].data) + ",\"version\":" + JSON.stringify(data.info[i].version) + "}");
				}
			}
			if(callback != undefined && callback != null) {
				callback();
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			return;
		}
	});
}
//定义字段
var store = window.localStorage;
/**
 * Description:获取codeclass当前缓存版本信息
 * @param codeclass
 * @returns
 */
function getCodeClassVersion(codeclass) {
	var codeclass_json = store.getItem(codeclass);

	if(codeclass_json == undefined) {
		return -1;
	}
	if(typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	if(!codeclass_json.data) {
		return -1;
	}

	return codeclass_json.version;
};

/**
 * Description: 获取codedesc,未找到对应desc返回undefined
 * @param codeclass
 * @param code
 * @returns
 */
function getCodeDescByCodeClass(codeclass, code) {
	if(!code) return code;
	var codes = code.split(",");
	var codeclass_json = store.getItem(codeclass);
	if(!codeclass_json) return code;
	if(typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	var code_arr = codeclass_json.data;
	if(codeclass_json.data == undefined) {
		code_arr = codeclass_json;
	}
	var codesdesc = "";
	for(var i = 0; i < code_arr.length; i++) {
		for(var j = 0; j < codes.length; j++) {
			if(code_arr[i].code == codes[j].replace(/(^\s*)|(\s*$)/g, "")) {
				codesdesc += code_arr[i].codedesc + ",";
			}
		}
	}
	if(codesdesc != "") {
		return codesdesc.substring(0, codesdesc.length - 1);
	} else {
		return code;
	}
};

/**
 * 设置默认头像
 * 
 * */
function setDefalutPhoto(value) {
	var photo = "../../../ui/common/images/moren1.png";
	if(!isEmpty(value)) {
		photo = filesHost + value;
	} else {
		photo = "../../../ui/common/images/moren1.png";

	}

	return photo;
}
/**
 * 非空判断
 * 判断传入值是否为 null，undefined，“”,返回true/false
 * */
function isEmpty(value) {
	var flg = false;
	if(value === undefined || value === "" || value === null || value === "none" || value === NaN) {
		flg = true;
	}

	return flg;
}
/**
 * 非空判断
 * 传入数组判断
 * */
function isEmptyArray(value) {
	var flg = false;
	for(var i = 0; i < value.length; i++) {
		if(isEmpty(value[i])) {
			flg = true;
			console.log("入参第" + (i + 1) + "个位空，或不存在");
			break;
		}
	}
	return flg;
}

/**
 * 非空判断
 * 传入数组判断
 * */
function getEmptyIndexByArray(value) {
	var index = -1;
	for(var i = 0; i < value.length; i++) {
		if(isEmpty(value[i])) {
			index = i;
			break;
		}
	}
	return index;
}

/**
 * 网络判断
 * */
function getNetWorkState() {
	var netStateStr = '未知';
	var types = {};
	types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
	types[plus.networkinfo.CONNECTION_NONE] = "无网络";
	types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
	types[plus.networkinfo.CONNECTION_WIFI] = "WiFi";
	types[plus.networkinfo.CONNECTION_CELL2G] = "2G";
	types[plus.networkinfo.CONNECTION_CELL3G] = "3G";
	types[plus.networkinfo.CONNECTION_CELL4G] = "4G";
	netStateStr = types[plus.networkinfo.getCurrentType()];
	return netStateStr;
};

function isHaveNet() {
	var flg = true;
	var netStateStr = getNetWorkState()
	if(netStateStr == "未知" || netStateStr == "无网络") {
		flg = false;
	}
	return flg;
}

/***
 *  根据传入的文件类型，返回对应的横版image图标SRC 
 * @param {Object} fileType :文件类型
 */
/***
 * 根据传入的文件类型，返回对应的竖版image图标SRC 
 */
function getBigIconByType(fileList, position) {
	var fileInfo = fileList[position];
	var gs1 = fileInfo.format;
	return getBigIconByFormat(gs1, fileInfo);
}

function getBigIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if(gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if(fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 'file_image.png';
		}
	} else if(gs == 'xls' || gs == 'xlsx') {
		return src + 'file_xls.png';
	} else if(gs == 'flv' || gs == 'swf') {
		return src + 'file_ani.png';
	} else if(gs == 'flash') {
		return src + 'file_flash.png';
	} else if(gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 'file_audio.png';
	} else if(gs == 'doc' || gs == 'docx') {
		return src + 'file_doc.png';
	} else if(gs == 'ppt' || gs == 'pptx') {
		return src + 'file_ppt.png';
	} else if(gs == 'txt') {
		return src + 'file_txt.png';
	} else if(gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 'file_video.png';
	} else if(gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 'file_zip.png';
	} else if(gs == 'pdf') {
		return src + 'file_pdf.png';
	} else if(gs == '') {
		return src + 'file_other.png';
	} else {
		return src + 'file_other.png';
	}
}

/**
 * 通过文件类型或去文件对应的小图标的方法
 * @param {Object} fileList 文件信息列表
 * @param {Object} position 选中的文件下标
 */
function getSmallIconByType(fileList, position) {
	var fileInfo = fileList[position];

	return getSmallIconByFormat(gs, fileInfo);
}

function getSmallIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if(gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if(fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 's_img.png';
		}

	} else if(gs == 'xls' || gs == 'xlsx') {
		return src + 's_xls.png';
	} else if(gs == 'flv' || gs == 'flash' || gs == 'swf') {
		return src + 's_animate.png';
	} else if(gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 's_audio.png';
	} else if(gs == 'doc' || gs == 'docx') {
		return src + 's_word.png';
	} else if(gs == 'ppt' || gs == 'pptx') {
		return src + 's_ppt.png';
	} else if(gs == 'txt') {
		return src + 's_cource.png';
	} else if(gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 's_video.png';
	} else if(gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 's_zip.png';
	} else if(gs == 'pdf') {
		return src + 's_pdf.png';
	} else if(gs == '') {
		return src + 's_other.png';
	} else {
		return src + 's_other.png';
	}
}

/**
 * 文件上传调用的方法
 */
//传入参数
//files：文件地址数组
//upload_abs_path： "wdcloud-rrt/rest/fileWS/upload"文件服务器上传接口 
//successCallBack:function(data)  上传成功时的回调函数 data参数为服务器返回的json数据
//failCallBack:function(status)  上传失败时的回调函数
//cd  附件的长度
/**
 * @修改时间 2016/09/22 19:20
 * 修改者:zgq
 * 修改内容:增加一个参数:num_i :第几张图片
 * 照片上传修改为多张上传
 */
var uploadhost = getRequestAddressUrl("filesUploader");
var upload_abs_path = "upload";

var sucess_num = 0;
var fail_num = 0;

function uploadFiles(settings, cd, num_i) {
	if(!settings) {
		console.log("传入参数不存在");
		return;
	};
	//	var w = plus.nativeUI.showWaiting();
	if(!isEmpty(num_i)) {
		if(num_i == cd) {
			mui.toast("正在上传文件...");
		}
	} else {
		mui.toast("正在上传文件...");
	}
	var files = settings.files;
	if(files.length <= 0) {
		plus.nativeUI.alert("没有添加上传文件！");
		return;
	}
	if(settings.upload_abs_path) {
		upload_abs_path = settings.upload_abs_path;
	}
	console.log("hostpath--->>" + uploadhost + upload_abs_path);
	var task = plus.uploader.createUpload(uploadhost + upload_abs_path, {
			method: "POST"
		},
		function(t, status) { //上传完成 
			console.log(t.responseText);
			console.log("status->" + status);
			if(status == 200) {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传成功");
				var resp = JSON.parse(t.url); // 干些后续处理
				if(settings.successCallBack) {
					settings.successCallBack.call('', resp);
				}
				sucess_num++;
				if((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			} else {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传失败：");
				if(settings.failCallBack) {
					settings.failCallBack.call('', status);
				}
				fail_num++;
				if((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			}
		}
	);

	if(files.length > 1) {
		for(var i = 0; i < files.length; i++) {
			var f = files[i];
			var path = plus.io.convertAbsoluteFileSystem(f);
			console.log("----filedizhi----------->" + f.toString());
			var length = f.split("/").length - 1;
			var key = f.split("/")[length];
			console.log("fileskey---->>" + key);

			task.addFile(path, {
				key: "files"
			});
			task.addData();
			task.start();
		}
	} else {
		var f = files[0];
		var path = plus.io.convertAbsoluteFileSystem(f);
		console.log("----filedizhi----------->" + f.toString());
		var length = f.split("/").length - 1;
		var key = f.split("/")[length];
		console.log("fileskey---->>" + key);
		task.addFile(path, {
			key: key
		});
		task.addData();
		task.start();
	}

	//	if(task) {
	//		task.start();
	//	} else {
	//		console.log("任务创建失败");
	//	};

}
/**
 * 
 * kb转mb
 */
function kBToMB(b) {
	if(isEmpty(b)) { //b shi kong
		return("0B");
	}
	b = parseInt(b);
	var kb = "";
	var mb = "";
	var gb = "";
	if(b < 1024) { //b
		return(b + "B");
	} else if(b >= 1024 && b < (1024 * 1024)) { //k
		if(b % 1024 == 0) {
			kb = b / 1024;
		} else {
			kb = Math.round(b / 1024);
		}
		return kb + "KB";
	} else if(b >= (1024 * 1024) && b < (1024 * 1024 * 1024)) { //m
		if(b % (1024 * 1024) == 0) {
			mb = b / (1024 * 1024);
		} else {
			mb = Math.round(b / (1024 * 1024));
		}
		return mb + "M";
	} else { //G
		if(b % (1024 * 1024 * 1024) == 0) {
			gb = b / 1024 / 1024 / 1024;
		} else {
			gb = gb + "";
			var i = gb.indexOf(".");
			gb = gb.substring(0, i + 2);
		}
		return gb + "G";
	}
}
/**
 * 
 * 四舍五入
 */
function rounding(size) {
	var size = size + "";
	var num = "";
	if(size.length >= 3) {
		var third = size.substring(2, 3);
		size = size.substring(0, 1);
		num = parseInt(size);
		if(third > 5) {
			num = num + 1;
		}
	} else {
		num = parseInt(size);
	}
	return num;
}
/**
 * 
 * 年-月-日
 */
function timeFormat(time) {
	var time = time + "";
	if(time == null || time == undefined || time == "") {
		time = ""
		return time;
	}

	if(time.length > 10) {
		time = time.substring(0, 10);
	}
	return time;
}
/**
 * 获取拼接的eq
 * @param {Object} array
 */
function getEqString(myMap) {
	var eqStr = "";

	for(var i = 0; i < myMap.length; i++) {
		if(!isEmpty(myMap[i].text) && !isEmpty(myMap[i].value) && myMap[i].text != "undefined" && myMap[i].value != "undefined") {
			eqStr = eqStr + myMap[i].text + ":" + myMap[i].value + ";";
		}
	}
	if(!isEmpty(eqStr)) { //有值
		eqStr = eqStr.substring(0, eqStr.length - 1);
	}
	return eqStr;
}
/**
 * 入参check
 * @param {Object} jsondate
 */
function checkParams(jsondate) {
	var jsonStr = "{";
	var returnFlag = false;
	for(var x in jsondate) {
		if(jsondate[x] == undefined || jsondate[x] == null) {
			console.log(x + "入参为空");
			returnFlag = true;
		}
	}
	return returnFlag;
}
/**
 * 资源路径的check
 */
function checkZylj(beforeSubStr) {
	var zylj = "";
	if(beforeSubStr.indexOf("http") > -1) {
		zylj = beforeSubStr;
	} else if(beforeSubStr.length > 0) {
		zylj = filesHost + beforeSubStr;
	}
	return zylj;
}
/**
 * 删除原有的list（刷新用）
 */
function removeLi(id) {
	var objUl = document.getElementById(id);

	if(objUl) {
		var objLi = objUl.getElementsByTagName("li");
		var length = objLi.length;
		for(var i = 0; i < length; i++) {
			objUl.removeChild(objLi[0]);
		}
	} else {
		mui.toast("刷新失败");
	}
}

function showEle(ele) {
	if(ele.classList.contains("mui-hidden")) {
		ele.classList.remove("mui-hidden");
	}
}

function hiddenEle(ele) {
	if(!ele.classList.contains("mui-hidden")) {
		ele.classList.add("mui-hidden");
	}
}

function hiddenEleByParent(parentEle, targetEle) {
	var eleArr = parentEle.getElementsByTagName(targetEle);
	for(var i = 0; i < eleArr.length; i++) {
		if(!eleArr[i].classList.contains("mui-hidden")) {
			eleArr[i].classList.add("mui-hidden");
		}
	}
}

function isShow(ele) {
	if(ele.classList.contains("mui-hidden")) {
		return false;
	} else {
		return true;
	}
}

function addClass(className, ele) {
	if(!ele.classList.contains(className)) {
		ele.classList.add(className)
	}
}

function deleteClass(className, ele) {
	if(ele.classList.contains(className)) {
		ele.classList.remove(className)
	}
}

/**
 * 错误信息弹窗 
 * @param {Object} data
 * @param {Object} code
 */
function toastMesg(data, code1, code2) {
	if(!isEmpty(data)) {
		if(!isEmpty(data.code)) {
			if(code1 > data.code || code2 <= data.code) {
				mui.toast(data.mesg);
			}
		}
	}
}

/**
 *日志打印方法  logFlag控制日志打印
 */
var logFlag = true;

function logText(text) {
	if(logFlag) {
		console.log(text);
	}
}

function formatTimeForTimestamp(timestamp) {
	var date = new Date(timestamp); //获取一个时间对象
	var year = date.getFullYear(); // 获取完整的年份(4位,1970)
	var month = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
	var day = date.getDate(); // 获取日(1-31)
	var hours = date.getHours(); // 获取小时数(0-23)
	var minutes = date.getMinutes(); // 获取分钟数(0-59)
	var seconds = date.getSeconds(); // 获取秒数(0-59)
	return year + "-" + month + '-' + day;
}

// 浮点数求和
function addFloat(a, b) {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch(f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch(f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
}

// 浮点数相减
function subFloat(a, b) {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length;
	} catch(f) {
		c = 0;
	}
	try {
		d = b.toString().split(".")[1].length;
	} catch(f) {
		d = 0;
	}
	return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
}

// 浮点数相乘
function mulFloat(a, b) {
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length;
	} catch(f) {}
	try {
		c += e.split(".")[1].length;
	} catch(f) {}
	return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}

// 浮点数相除
function divFloat(a, b) {
	var c, d, e = 0,
		f = 0;
	try {
		e = a.toString().split(".")[1].length;
	} catch(g) {}
	try {
		f = b.toString().split(".")[1].length;
	} catch(g) {}
	return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mulFloat(c / d, Math.pow(10, f - e));
}
/***
 * 将图片转换为base64编码格式 
 * @param {Object} img
 */
function getBase64Image(img, maxHeight, coefficient) {
	var canvas = document.createElement("canvas");
	//	if(img.height > maxHeight) {
	//		img.width *= maxHeight / img.height;
	//		img.height = maxHeight;
	//	}
	canvas.width = img.width;
	canvas.height = img.height;
	var ctx = canvas.getContext("2d");
	ctx.drawImage(img, 0, 0, img.width, img.height);
	var dataURL = canvas.toDataURL("image/png", coefficient);
	return dataURL.replace("data:image/png;base64,", "");
}